<template>
  <el-dialog
    :title="'上传' + typeText"
    :visible="visible"
    width="900px"
    :before-close="handleClose"
    append-to-body
  >
    <el-form
      ref="form"
      label-position="left"
      :model="upload"
      label-width="80px"
      class="upload-video"
    >
      <el-form-item label="上传到">
        <el-select v-model="upload.category" placeholder="请选择分组" size="small">
          <el-option
            v-for="item in categoryList"
            :key="item.id"
            :label="item.title"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="选择文件">
        <el-upload
          ref="upload"
          class="upload-container"
          action=""
          :accept="accept"
          multiple
          :limit="limit"
          :auto-upload="false"
          :http-request="fileUpload"
          :on-progress="fileOnProgress"
          :on-change="fileOnChange"
          :on-remove="fileOnRemove"
          :on-success="fileOnSuccess"
          :show-file-list="false"
          :on-exceed="onExceed"
        >
          <el-button slot="trigger" size="small" type="primary">选取{{ typeText }}</el-button>
          <div slot="tip" class="el-upload__tip">
            最多可上传{{ limit }}个文件
            <span v-if="limit > 1">，按住Ctrl可以多选</span>
          </div>
        </el-upload>
        <el-table :data="uploadListInfo" style="width: 100%" height="250">
          <el-table-column prop="name" label="文件名" />
          <el-table-column prop="size" label="大小" />
          <el-table-column prop="status" label="上传状态" />
          <el-table-column prop="action" label="操作">
            <template slot-scope="scope">
              <el-link :underline="false" type="primary" @click="removeFile(scope.row.name)"
                >移除</el-link
              >
            </template>
          </el-table-column>
        </el-table>
      </el-form-item>
    </el-form>
    <el-row slot="footer" type="flex" justify="center">
      <el-button
        type="primary"
        :disabled="disableSubmit"
        size="small"
        @click="submitUpload"
        v-text="btnText"
        >确认上传</el-button
      >
    </el-row>
  </el-dialog>
</template>

<script>
export default {
  props: {
    visible: Boolean,
    type: [String, Number],
    limit: {
      type: Number,
      default: 100
    },
    category: Array
  },
  data() {
    return {
      upload: {
        category: -1
      },
      uploadType: {
        1: 'image/*',
        2: 'audio/*',
        3: 'video/*',
        4: '.pdf'
      },
      btnText: '确认上传',
      disableSubmit: false,
      uploadList: [],
      uploadListInfo: [],
      attach_ids: [],
      uploading: 0,
      timer: 0
    }
  },
  computed: {
    categoryList() {
      let list = this.category.filter(item => {
        if (item.id !== 0) {
          return item
        }
      })
      return list
    },
    accept() {
      return this.uploadType[this.type]
    },
    typeText() {
      const text = {
        1: '图片',
        2: '音频',
        3: '视频',
        4: '文档'
      }
      return text[this.type]
    }
  },
  methods: {
    handleClose() {
      this.$emit('update:visible', false)
    },
    // 格式化文件大小
    renderSize(value) {
      if (!value) {
        return '0 Bytes'
      }
      var unitArr = ['Bytes', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB']
      var index = 0
      var srcsize = parseFloat(value)
      index = Math.floor(Math.log(srcsize) / Math.log(1024))
      var size = srcsize / Math.pow(1024, index)
      size = size.toFixed(2) // 保留的小数位数
      return size + unitArr[index]
    },
    /** 手动点击上传方法 */
    submitUpload() {
      if (this.uploadList.length == 0) {
        this.$message.warning('请选择要上传的素材')
        return false
      }
      clearInterval(this.timer)
      this.btnText = '正在上传...'
      this.disableSubmit = true

      this.uploading = this.uploadList.length
      this.$refs.upload.submit()
      // 全部上传完成时,提交素材
      this.timer = setInterval(() => {
        // 只有全部上传完成时,再提交
        if (this.attach_ids.length != this.uploading) {
          return false
        }
        clearInterval(this.timer)
        // 提交绑定素材
        this.$api.postUserTeacherMaterialAdd(
          {
            type: this.type,
            cate_id: this.upload.category,
            attach_ids: this.attach_ids.toString()
          },
          response => {
            this.$message.success(response.msg)
            this.handleClose()
            this.$emit('reload')
            this.btnText = '上传成功'
            this.disableSubmit = false
          },
          error => {
            this.$message.error(error.msg)
          }
        )
      }, 200)
    },
    onExceed() {
      this.$message.error('最多一次性上传' + this.limit + '个文件')
    },
    /** 自定义文件上传方法,采用分片上传 */
    fileUpload(params) {
      // 分片上传 每2M为一片
      this.$upload.submit(params, true, 2)
    },
    fileOnChange(file, fileList) {
      if (file.status === 'ready') {
        const existFile = fileList.slice(0, fileList.length - 1).find(f => f.name === file.name)
        existFile && fileList.pop()
      }
      this.uploadList = fileList
      this.updateUploadListInfo(fileList)
    },
    fileOnRemove(file, fileList) {
      const attachId = file.id || (file.response ? file.response.data.id : 0)
      attachId && this.setValue(attachId, false)
    },
    fileOnProgress(event, file, fileList) {
      const current = this.uploadListInfo.find(item => item.name == event.name)
      current.status = event.percent + '%'
    },
    fileOnSuccess(response, file, fileList) {
      const attachId = file.id || response.data.id
      this.setValue(attachId, true)
    },
    setValue(attachId, action) {
      if (action === true) {
        // 添加
        this.attach_ids.push(attachId)
      } else {
        this.attach_ids.splice(
          this.attach_ids.findIndex(item => item === attachId),
          1
        )
      }
    },
    removeFile(name) {
      this.uploadList.splice(
        this.uploadList.findIndex(item => item.name == name),
        1
      )
      this.updateUploadListInfo(this.uploadList)
    },
    updateUploadListInfo(fileList) {
      this.uploadListInfo = []
      fileList.forEach(file => {
        let status = '待上传'
        switch (file.status) {
          case 'ready':
            status = '待上传'
            break
          case 'success':
            status = '上传完成'
            break
        }
        const item = {
          name: file.name,
          size: this.renderSize(file.size),
          status: status,
          action: ''
        }

        this.uploadListInfo.push(item)
      })
    }
  }
}
</script>

<style lang="scss" scoped>
::v-deep .el-dialog__header {
  border-bottom: 1px solid #e4e7ed;
}
</style>
